<template>
  <div style="height: 100%">
    <div class="map-container">
      <div class="header">
        <span class="title">订单区划聚合统计</span>
        <div class="select-date">
          <el-date-picker
            v-model="startDate"
            type="month"
            placeholder="请选择开始月份"
          ></el-date-picker>
          <el-date-picker
            v-model="endDate"
            class="margin-left-5"
            type="month"
            placeholder="请选择结束月份"
          ></el-date-picker>
        </div>
        <div class="btn-ground">
          <el-button type="default" @click="reset()">重置</el-button>
          <el-button
            type="primary"
            @click="loadData()"
            :loading="loading"
            style="margin-left: 20px"
            >查询</el-button
          >
        </div>
        <div class="totals">
          当前订单总量：
          <span>{{ totals || 0 }}</span> 单
        </div>
      </div>
      <el-amap
        ref="map"
        v-loading="loading"
        element-loading-text="数据查询中，请等待.."
        class="ngxmap"
        vid="amap"
      ></el-amap>
    </div>
    <!-- 折叠画板开关按钮 -->
    <!--     <div
      class="switch-btn"
      :class="{'btn-up-site':showBox,'btn-down-site':!showBox}"
      @click="handleSwitch"
    >
      <i nz-icon :class="{'hide':!showBox}">
        <svg
          t="1573793010629"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="857"
          width="16"
          height="16"
        >
          <path
            d="M247.637333 480.199111a28.444444 28.444444 0 1 0-40.163555 40.391111l284.444444 283.136a28.444444 28.444444 0 0 0 40.163556 0l284.444444-283.192889a28.444444 28.444444 0 1 0-40.163555-40.334222L512 743.424 247.637333 480.142222z"
            fill="#ffffff"
            p-id="858"
          />
          <path
            d="M247.637333 252.643556a28.444444 28.444444 0 0 0-40.163555 40.391111l284.444444 283.136a28.444444 28.444444 0 0 0 40.163556 0l284.444444-283.192889a28.444444 28.444444 0 1 0-40.163555-40.334222L512 515.868444 247.637333 252.586667z"
            fill="#ffffff"
            p-id="859"
          />
        </svg>
      </i>
      <i :class="{'hide':showBox}">
        <svg
          t="1573793528777"
          class="icon"
          viewBox="0 0 1024 1024"
          version="1.1"
          xmlns="http://www.w3.org/2000/svg"
          p-id="1759"
          width="16"
          height="16"
        >
          <path
            d="M247.637333 543.800889a28.444444 28.444444 0 1 1-40.163555-40.391111l284.444444-283.136a28.444444 28.444444 0 0 1 40.163556 0l284.444444 283.192889a28.444444 28.444444 0 1 1-40.163555 40.334222L512 280.576 247.637333 543.857778z"
            fill="#ffffff"
            p-id="1760"
          />
          <path
            d="M247.637333 771.356444a28.444444 28.444444 0 0 1-40.163555-40.391111l284.444444-283.136a28.444444 28.444444 0 0 1 40.163556 0l284.444444 283.192889a28.444444 28.444444 0 1 1-40.163555 40.334222L512 508.131556 247.637333 771.413333z"
            fill="#ffffff"
            p-id="1761"
          />
        </svg>
      </i>
    </div>-->
  </div>
</template>

<script>
import { Observable, Subject, zip } from 'rxjs';
import * as moment from 'moment';
import MapApiLoadService from '../shared/map-api-loader';
import { PROVINCES } from '../shared/config';
import { warningToast, errorToast } from '../shared/message';
import './style.scss';
import { AMapManager } from 'vue-amap';
const amapManager = new AMapManager();
const mapApiLoader = new MapApiLoadService();
export default {
  name: 'visual-cluster',
  props: {
    msg: String
  },
  data() {
    this._subject$ = new Subject();
    return {
      amapManager,
      endDate: null,
      startDate: null,
      showBox: false,
      loading: false,
      totals: 0
    };
  },
  computed: {
    map() {
      // return this.amapManager._map;
      return this.$refs.map.$amap;
    }
  },
  mounted() {
    this.initDate();
    this.loadData();
  },
  methods: {
    handleSwitch() {
      this.showBox = !this.showBox;
    },
    reset() {},
    loadData() {
      const monthsRange = this.calculateMonths();
      this.queryData(monthsRange);
    },

    initCluster(lnglat) {
      mapApiLoader.load(['geo/DistrictCluster']).then((DistrictCluster) => {
        window.DistrictCluster = DistrictCluster;
        console.log(this.map);
        this.distCluster = window.distCluster = new DistrictCluster({
          map: this.map, //所属的地图实例
          zIndex: 11,
          getPosition: (item) => {
            if (!item) {
              return null;
            }
            let parts = [];
            if (typeof item.split !== 'function' && Array.isArray(item)) {
              parts = [...item];
              return [parseFloat(parts[0]), parseFloat(parts[1])];
            }
            parts = item.split(',');
            //返回经纬度
            return [parseFloat(parts[0]), parseFloat(parts[1])];
          }
        });
        this.distCluster.setData(lnglat);
        this.clusterRecordResult(); //  根据省code获取数据
      });
    },

    genObservable(monthList) {
      const obsReqList = [];
      this.monthsNumber = [];
      for (let mon of monthList) {
        const obsReq = new Observable((observer) => {
          // const url = BASE_URL || '';
          // 因gitee部署的时候不识别txt文件，所以改为 .html
          fetch(`data/${mon}.html`, {
            method: 'GET',
            mode: 'no-cors'
          })
            .then((resp) => {
              return resp.text();
            })
            .then((text) => {
              const positionList = text.split('\n');
              this.monthsNumber.push({
                name: mon,
                number: positionList.length
              }); //获取月份对应的订单量
              observer.next(positionList);
            });
        });
        obsReqList.push(obsReq);
      }
      return obsReqList;
    },

    queryData(dateArray) {
      let monthReqs = this.genObservable(dateArray);

      this.loading = true;
      zip(...monthReqs).subscribe(
        (data) => {
          warningToast('地图数据渲染中……', 2000);
          let tempArr = [];
          for (let arr of data) {
            tempArr = tempArr.concat(arr);
          }
          this.loading = false;
          this.totals = tempArr.length;
          this.initCluster(tempArr);
        },
        () => {
          errorToast('订单坐标数据获取失败');
          this.loading = false;
        }
      );
    },
    // 第一个参数为政区code，440000 为广东省的，第二个为回调参数，res为获取到的数据结果  ---- 异步处理
    // this.distCluster.getClusterRecord(440000,(err,res)=>console.log(err,res))
    queryDataClusterRecord() {
      const allPromise = (PROVINCES || []).map((item) => {
        return new Promise((resolve) => {
          this.distCluster.getClusterRecord(item['code'], (err, res) => {
            resolve({
              adcode: res.adcode,
              name: res.name,
              number: res.dataItems.length
            });
          });
        });
      });
      return Promise.all(allPromise || []);
    },

    async clusterRecordResult() {
      this.provincesData = (await this.queryDataClusterRecord()) || [];
      const arr = this.provincesData.sort((a, b) =>
        a.number > b.number ? 1 : -1
      );
      this._subject$.next(arr);
    },

    initDate() {
      this.startDate = new Date('2019/06');
      this.endDate = new Date('2019/09');
      return ['2019/06', '2019/09'];
    },
    calculateMonths() {
      if (!this.startDate || !this.endDate) {
        return this.initDate();
      }
      const dateArr = [];
      const startDateStr = moment(this.startDate);
      const endDateStr = moment(this.endDate);
      const dateIff = endDateStr.diff(startDateStr, 'months'); //计算两月份间差值
      for (let i = 0; i <= dateIff; i++) {
        dateArr.push(moment(this.startDate).add(i, 'months').format('YYYY/MM'));
      }
      return dateArr;
    }
  }
};
</script>

 
